const { SerialPort } = require('serialport')
const { ByteLengthParser } = require('@serialport/parser-byte-length')

const {uart2battery} = require('./config.js')

const data={}
let port = null 
module.exports = data

if(uart2battery ==undefined){
    module.exports={Err:'No uart config~~~~'}
}else{
    

port = new SerialPort({ path: uart2battery.dev_name,
                                baudRate: uart2battery.baud,
                                autoOpen: true})

const parser = port.pipe( new ByteLengthParser({ length: 1 }) )    

const respon_msg=[]
parser.on('data',bb =>{
    respon_msg.push(bb[0])
    if(respon_msg.length==1 && respon_msg[0]!= 0x7f){
        respon_msg.length=0
        return 
    }

    if(respon_msg.length==5 && respon_msg[4]!= 0x12){
        respon_msg.length=0
        return 
    }

    if(respon_msg.length == respon_msg[3]){
		//console.warn("回复消息:",respon_msg)
		//output(respon_msg)
        if(check_sum(respon_msg)==false){
            console.warn('回复消息校验失败!')
            respon_msg.length=0
            return 
        }
        
        console.log('收到回复消息')
        data.status=[]
        for(let i=0;i<4;i++) data.status.push(respon_msg[i+5])
        try{
            const Buffer = new Uint8Array(respon_msg)
            const cur_data = new DataView(Buffer.buffer,9,2)
        
            data.current = cur_data.getInt16(0,true) //respon_msg[10]*256 + respon_msg[9]
        
            data.cellNum = respon_msg[11]
            
            data.cellVolt = []
            for(let i=0; i< data.cellNum*2; i+=2) data.cellVolt.push(respon_msg[i+13]*256 + respon_msg[i+12])
            
            data.remainQ = respon_msg[respon_msg.length-5]*256 + respon_msg[respon_msg.length-6]
            
            data.totalQ  = respon_msg[respon_msg.length-3]*256 + respon_msg[respon_msg.length-4]
            
            data.swStatus = respon_msg[respon_msg.length-2]
            //console.log(data)
            //module.exports = data
        }catch(err){
            console.error('数据处理出错',err)
        }
        respon_msg.length = 0
    }

})

}

function output(arr){
	
	const len=arr.length
	console.log('[')
	for(let i=0;i<len; i++){
		//console.log(arr[i].toString(16),',')
		 process.stdout.write(arr[i].toString(16)+',')
	}
	console.log(']')
}

setInterval(()=>{
    const msg=[0x7f,0x10,2,6,0x12,0x57]
    console.log("发送查询命令:",msg)
    port.write(msg)

},10*1000)  //每隔10秒发送一次查询


function check_sum(data){
    let sum=0
    for(let i=0; i<data.length-1; i++)
        sum += data[i]

    if(((~sum)&0xff)+1 == data[data.length-1]){
		return true 
	} 
    
    return false 
}